package com.alisonyu.spider.cluster;

import com.alisonyu.spider.Downloader.Request;
import com.alisonyu.spider.Scheduler.Schedule;
import com.alisonyu.spider.Scheduler.SimpleMemoryScheduler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

public class ClusterServerVerticle extends AbstractVerticle {
    private EventBus eb;
    private Schedule scheduler;
    private Logger logger  = LoggerFactory.getLogger(ClusterServerVerticle.class);
    private final JsonObject emptyResult = new JsonObject().put("status",0);

    public ClusterServerVerticle(){
        this.scheduler = new SimpleMemoryScheduler();
    }

    public ClusterServerVerticle(Schedule scheduler){
        this.scheduler = scheduler;
    }

    @Override
    public void start(){
        this.eb = vertx.eventBus();
        registerEvents();
        logger.info("ClusterServer启动成功");
    }

    private void registerEvents(){
        eb.consumer("request.get",this::getUrl);
        eb.consumer("request.put",this::putRequest);
    }

    /**
     * 添加request
     * @param message
     */
    public void putRequest(Message<JsonObject> message){
        message.reply(emptyResult);
        JsonObject body = message.body();
        Request request = Request.toRequest(body);
        if (request == null) return;
        scheduler.putRequest(request);
    }

    /**
     * 返回一下Json{
     *     status：0 or 1(0代表无数据，1代表成功获取数据)
     *     request:JsonObject
     * }
     * @param message
     */
    public void getUrl(Message<JsonObject> message){
        Request rq = scheduler.getRequest();
        if(rq==null){
            message.reply(emptyResult);
            return;
        }
        JsonObject json = requestJsonResult(rq);
        message.reply(json);
    }

    private JsonObject requestJsonResult(Request request){
        JsonObject jsonObject = new JsonObject();
        jsonObject.put("status",1);
        jsonObject.put("request",request.toJsonObject());
        return jsonObject;
    }

}
